import router from "@/router";
import type { DatePickerProps } from "ant-design-vue";
import type { FormInstance, RuleObject } from "ant-design-vue/es/form";

type RangeChangeParameters = Parameters<Required<DatePickerProps>['onChange']>;
type HandleRangeChangeMeta = {
  start: string;
  end: string;
  type: 'empty' | 'full' | 'semi';
  dateStrings: string[];
};
/** handle RangePicker onChange */
export const handleRangeChange = function (dates: RangeChangeParameters['0'][], dateStrings: RangeChangeParameters['1'][], onConfirm: (meta: HandleRangeChangeMeta) => any) {
  const meta: HandleRangeChangeMeta = {
    dateStrings,
    type: 'empty',
    start: '',
    end: '',
  };
  if (!dates || dates.length === 0) {
    // no-op, use empty
  }
  if (dates) {
    const [date1, date2] = dates;
    const isDayjs = dateUtil.isDayjs(date1);
    if (dates.length === 2) {
      // @ts-ignore
      meta.start = isDayjs ? dateFormat(startOfDay(date1), "rangeValue") : date1;
      // @ts-ignore
      meta.end = isDayjs ? dateFormat(endOfDay(date2), "rangeValue") : date2;
      meta.type = 'full';
    } else if (dates.length === 1) {
      meta.type = 'semi';
      // @ts-ignore
      meta.start = isDayjs ? dateFormat(startOfDay(date1), "rangeValue") : date1;
    }
  }
  onConfirm(meta);
};
export function toLogin(opts?: { redirected?: string; reload?: boolean; }) {
  const redirected = opts?.redirected ?? router.currentRoute.value.fullPath
  if (opts?.reload) {
    const resolved = router.resolve({ name: 'Login', query: { redirected } })
    window.location.replace(resolved.fullPath)
  } else {
    router.replace({ name: 'Login', query: { redirected } })
  }
}
export function getPasswordRules<FormState extends { password?: string; password2?: string; }>(formState: IFn<FormState>, formRef: IFn<INullable<FormInstance>>): { password: IArrayable<RuleObject>; password2: IArrayable<RuleObject>; } {
  return {
      password: [
          {
              required: true, validator(_, value) {
                  if (!value) {
                      return Promise.reject('请输入新密码');
                  } else if (value.length < 5 || value.length > 15) {
                      return Promise.reject('密码长度需在5~15个字符内');
                  } else if (/[^a-zA-Z0-9]/.test(value)) {
                      return Promise.reject('密码仅可包含字母和数字');
                  }else {
                      if (toValue(formState).password2 !== '') {
                          toValue(formRef)!.validateFields('password2');
                      }
                      return Promise.resolve();
                  }
              }, trigger: "change"
          },
      ],
      password2: [
          {
              validator(_, value) {
                  if (!value) {
                      return Promise.reject('请再次输入密码');
                  } else if (value !== toValue(formState).password) {
                      return Promise.reject("两次输入密码不一致");
                  } else {
                      return Promise.resolve();
                  }
              }, trigger: "change"
          }
      ]
  }
}
export function reload() {
  window.location.reload()
}
export function handleExternalLink() {
  const url = new URL(location.toString())
  const token = url.searchParams.get('token')
  if (token) {
    setStorageToken(token)
    url.searchParams.delete('token')
    window.location.replace(url)
  }
}
export function formatDuration(duration: number) {
  const hours = Math.trunc(duration / (60 * 60));
  duration = duration % (60 * 60);
  const minutes = Math.trunc(duration / 60);
  duration = duration % 60;
  return {
    hours,
    minutes,
    seconds: duration
  }
}
export function getLsKey(key: string) {
  return key.concat(LS_SUFFIX)
}
export function isAllValue(value: unknown) {
  return value === AllValue
}